var _upload_interval = 0;
function _uextend(obj,newAdd){
    for(var o in newAdd){
        obj[o] = newAdd[o];
    }
}
function _getWH(imgObj){
    var css = imgObj.currentStyle ||window.getComputedStyle(imgObj,null);
    if(css.width){
        return {width:parseInt(css.width),height:parseInt(css.height)};
    }

    if("img"==imgObj.tagName.toLowerCase()) {
        var temp = new Image();
        temp.src = imgObj.src;
        return {width: parseInt(temp.width), height: parseInt(temp.height)};
    }
}

var uploading = false;
function myUpload(ops){
    if(uploading){
        alert("正在处理，请稍等……");
        return;
    }

    var showId = ops.showId||"";
    var loadingHtml = ops.loadingHtml||"正在处理,请稍后...";
    var iframeId = ops.iframeId||"ifr123_456_789";
    var uploadUrl = ops.uploadUrl||"";
    var fieldName = ops.fieldName||"file";
    var onFinish = ops.onFinish||function(v){}
    var checkType = ops.checkType||function(v){return true;};
    var onError = ops.onError||function(v){alert(v);};

    /**提交表单**/
    function submitfile()
    {
        var temp = this.value;
        if(temp==""){
            return ;
        }
        //检查文件格式，jpg,gif,	png
        var extend=temp.substring(temp.lastIndexOf(".")+1).toLowerCase();

        if(!checkType(extend)){
            return;
        }


        if(!this.issubmited){
            this.issubmited=true;
            _upload_interval = new Date().getTime();
            if(""!=showId){
                var loading = document.getElementById(showId);

                var tag = loading.tagName.toLowerCase();
                var top = parseInt(loading.offsetTop);
                var left = parseInt(loading.offsetLeft);
                var temp = tag.parentNode;
                while(temp){
                    top += parseInt(temp.offsetTop);
                    left += parseInt(temp.offsetLeft);

                    temp = temp.parentNode;
                }

                var lc = document.getElementById("_up_cover_");
                if(lc==undefined){
                    lc = document.createElement("div");
                    lc.id = "_up_cover_";
                    lc.innerHTML = loadingHtml;
                    document.body.appendChild(lc);
                }
                var wh = _getWH(loading);
                _uextend(lc.style,{
                    position:"absolute",
                    width:wh.width+"px",
                    height:wh.height+"px",
                    left:left+"px",
                    top:top+"px",
                    backgroundColor:"#222222",
                    opacity:"0.5",
                    filter:"alpha(opacity=50)",
                    zIndex:"9",
                    textAlign:"center",
                    lineHeight:wh.height+"px",
                    color:"#FFFFFF",
                    display:"block"
                });
            }
            this.parentNode.submit();
            var i=0;
            var intervalflat = setInterval(function(){
                if(i>200){
                    clearInterval(intervalflat);
                    document.getElementById("_up_cover_").style.display="none";
                    alert("当前网速较慢，处理超时，请重试！");
                    return;
                }
                i++;
                var newField = document.getElementById(iframeId).contentWindow.document.getElementsByTagName("input");
                if(newField.length>1){
                    clearInterval(intervalflat);
                    var v = newField[1].value;
                    if(document.getElementById("_up_cover_"))document.getElementById("_up_cover_").style.display="none";
                    onError(v);

                    uploading = false;

                }else if(newField[0]&&(newField[0].type=="text"||newField[0].type=="hidden")){
                    clearInterval(intervalflat);

                    if(document.getElementById("_up_cover_"))document.getElementById("_up_cover_").style.display="none";
                    onFinish(newField[0].value);
                    uploading = false;
                }
            },200);
        }
    }


    function selFile()
    {
        /**创建一个隐形上传页面**/
        var ifrm = document.getElementById(iframeId);
        if(ifrm){
            ifrm.parentNode.removeChild(ifrm);
            ifrm = null;
        }

        ifrm = document.createElement("iframe");
        ifrm.src="about:blank";
        ifrm.style.display="none";
        document.body.appendChild(ifrm);
        ifrm.id = iframeId;
        ifrm.contentWindow.document.write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><title></title></head><body><form id='imgfrm' enctype='multipart/form-data' method='post' action='"+uploadUrl+"' target='_self'><input type='file' name='"+fieldName+"'/></form></body></html>");

        var f=ifrm.contentWindow.document.getElementsByTagName("input")[0];

        f.issubmited=false;

        /**文件域的值改变后绑定提交表单事件**/
        if(f.attachEvent)
        {
            f.onpropertychange=submitfile;
        }
        else
        {
            f.addEventListener("change",submitfile,false);
        }

        /**点击文件域，打开浏览文件对话框**/
        f.click();
    }

    selFile();
}

function myUpload2(ops){
    var fromId = ops.fromId||"from_123_456_789";
    var uploadUrl = ops.uploadUrl||"";
    var fieldName = ops.fieldName||"file";
    var onFinish = ops.onFinish||function(v){alert(v);};
    var onErr = ops.onErr||function(v){alert(v);};
    var checkType = ops.checkType||function(v){return true;};
    var fHtml = [];
    fHtml.push("<input id=\"_file\" name=\""+fieldName+"\"  type=\"file\" />");
    var form = document.getElementById(fromId);
    if(form==undefined){
        form = document.createElement("form");
        form.style.display="none";
        form.id=fromId
        form.action=uploadUrl;
        form.method="post";
        form.enctype="multipart/form-data";
        document.getElementsByTagName("body")[0].appendChild(form);
    }

    $(form).html(fHtml.join(""));

    //普通上传
    var new_upload = function() {

        var f = $("#_file");
        if (f[0].files.length <= 0) {
            alert("请选择文件！");
            return;
        }
        var n = f[0].files[0].name;
        var iIndex = n.lastIndexOf(".");
        var fix = n.substring(iIndex+1);
        if (!checkType(fix)) {
            return false;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', uploadUrl, true);
        var formData;
        formData = new FormData();
        formData.append(fieldName, f[0].files[0]);
        xhr.onreadystatechange = function(response) {
            if (xhr.readyState == 4 && xhr.status == 200
                && xhr.responseText != "") {
                onFinish(xhr.responseText);
            } else if (xhr.status != 200 && xhr.responseText) {
                onErr("上传文件出错，请稍后再试！");
            }
        };
        xhr.send(formData);
    };


    var f = document.getElementById("_file");
    if(f.attachEvent){
        f.onpropertychange=new_upload;
    }else{
        f.addEventListener("change",new_upload,false);
    }

    f.click();
}




function QiniuUpload(ops){
    var prefix = ops.prefix||"";
    var name = ops.name||prefix+new Date().getTime();
    var token = ops.token||"q9Z2omvM-8jgwetBmiqBwJcjcL7dYf4Tdj-vRZIa:3Qqya03WyIywvf7mAv4A_iTZB3k=:eyJzY29wZSI6ImRha2FxaSIsInJldHVybkJvZHkiOiJ7XCJidWNrZXRcIjoke2J1Y2tldH0sXCJrZXlcIjogJChrZXkpLFwibmFtZVwiOiAkKGZuYW1lKSxcInNpemVcIjogJChmc2l6ZSksXCJ0eXBlXCI6ICQobWltZVR5cGUpLFwiaGFzaFwiOiAkKGV0YWcpfSIsImRlYWRsaW5lIjoxMzk2NDI2NjY5fQ==";
    var successBack = ops.successBack||function(json){console&&console.info(json);};
    var fHtml = [];
    fHtml.push("<input id=\"token\" name=\"token\" class=\"ipt\" value=\""+token+"\">");
    fHtml.push("<input id=\"key\" name=\"key\"  value=\""+name+"\">");
    fHtml.push("<input id=\"file\" name=\"file\"  type=\"file\" />");
    var form = document.getElementById("qn_form");
    if(form==null){
        form = document.createElement("form");
        document.getElementsByTagName("body")[0].appendChild(form);
        form.id="qn_form";
        form.action="http://up.qiniu.com";
        form.method="post";
        form.enctype="multipart/form-data";

        form.style.display="none";
    }

    $(form).html(fHtml.join(""));


    /*
     *   本示例演示七牛云存储表单上传
     *
     *   按照以下的步骤运行示例：
     *
     *   1. 填写token。需要您不知道如何生成token，可以点击右侧的链接生成，然后将结果复制粘贴过来。
     *   2. 填写key。如果您在生成token的过程中指定了key，则将其输入至此。否则留空。
     *   3. 姓名是一个自定义的变量，如果生成token的过程中指定了ody，
     *      并且returnBody中指定了期望返回此字段，则七牛会将其返回给returnUrl对应的业务服务器。
     *      callbackBody亦然。
     *   4. 选择任意一张照片，然后点击提交即可
     *
     *   实际开发中，您可以通过后端开发语言动态生成这个表单，将token的hidden属性设置为true并对其进行赋值。
     *
     *  **********************************************************************************
     *  * 贡献代码：
     *  * 1. git clone git@github.com:icattlecoder/jsfiddle
     *  * 2. push代码到您的github库
     *  * 3. 测试效果，访问 http://jsfiddle.net/gh/get/jquery/1.9.1/<Your GitHub Name>/jsfiddle/tree/master/ajaxupload
     *  * 4. 提pr
     *   **********************************************************************************
     */
    //普通上传
    var Qiniu_upload = function() {
        var Qiniu_UploadUrl = "http://up.qiniu.com/";
        var token = $("#token").val();
        var key = $("#key").val();
        var f = $("#file");
        if (f[0].files.length <= 0 || token == "") {
            alert("缺少上传参数");
            return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', Qiniu_UploadUrl, true);
        var formData, startDate;
        formData = new FormData();
        if (key !== null && key !== undefined) formData.append('key', key);
        formData.append('token', token);
        formData.append('file', f[0].files[0]);
        var taking;
        xhr.onreadystatechange = function(response) {
            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
                var blkRet = JSON.parse(xhr.responseText);
                successBack(blkRet);
            } else if (xhr.status != 200 && xhr.responseText) {
                alert("上传文件出错，请稍后再试！");
            }
        };
        xhr.send(formData);
    };


    var f = document.getElementById("file");
    if(f.attachEvent){
        f.onpropertychange=Qiniu_upload;
    }else{
        f.addEventListener("change",Qiniu_upload,false);
    }

    f.click();
}


